package com.xiaoyu.lanling.feature.accost

import `in`.srain.cube.views.list.CubeRecyclerViewSimpleAdapter
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.utils.ListUtil
import com.xiaoyu.base.utils.extensions.dp
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.base.view.list.GridSpacingItemDecoration
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.BaseDialogFragment
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.event.accost.QuickAccostBatchEvent
import com.xiaoyu.lanling.event.accost.QuickAccostUserClickEvent
import com.xiaoyu.lanling.feature.accost.data.AccostData
import com.xiaoyu.lanling.feature.accost.model.QuickAccostUserItem
import com.xiaoyu.lanling.feature.accost.viewholder.QuickAccostUserViewHolder
import io.reactivex.functions.Function
import io.reactivex.functions.Predicate
import kotlinx.android.synthetic.main.quick_accost_dialog.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class QuickAccostDialogFragment : BaseDialogFragment() {

    companion object {
        private val TAG = QuickAccostDialogFragment::class.java.simpleName

        fun show(fragmentManager: FragmentManager, users: ArrayList<QuickAccostUserItem>) {
            val params = Bundle()
            params.putSerializable(Constant.IntentKey.KEY_QUICK_ACCOST_USERS, users)

            val dialogFragment = (fragmentManager.findFragmentByTag(TAG) as? QuickAccostDialogFragment)
                    ?: QuickAccostDialogFragment()
            dialogFragment.arguments = params
            dialogFragment.show(fragmentManager, TAG)
        }
    }

    private val requestTag = Any()
    private val adapter = CubeRecyclerViewSimpleAdapter<QuickAccostUserItem>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFullScreenDimStyle)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.quick_accost_dialog, container, false)
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        super.onViewCreatedSafelyAfterAppFinishInit(view, savedInstanceState)
        initAdapter()
        initBind()
        initEvent()
        initData()
    }

    private fun initAdapter() {
        adapter.setViewHolderClass(0, null, QuickAccostUserViewHolder::class.java, 6)
        recyclerview.adapter = adapter
        recyclerview.addItemDecoration(GridSpacingItemDecoration(3, 0, 16, false))
    }

    private fun initBind() {
        close.setOnClickDebounceListener { dismiss() }
        button.setOnClickDebounceListener {
            val toUids = ListUtil.convertToList(adapter.list, Predicate<QuickAccostUserItem> { item -> item.selected }, Function<QuickAccostUserItem, String> { item -> item.user.uid })
            AccostData.accostBatch(requestTag, toUids)
        }
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: QuickAccostUserClickEvent) {
                updateButtonStatus()
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: QuickAccostBatchEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                dismissDialog()
            }
        })
    }

    private fun showData(users: List<QuickAccostUserItem>) {
        adapter.list = users
        adapter.notifyDataSetChanged()

        updateButtonStatus()
    }

    private fun initData() {
        val users = (arguments?.getSerializable(Constant.IntentKey.KEY_QUICK_ACCOST_USERS) as? ArrayList<QuickAccostUserItem>)
        users?.let {
            showData(users)
        }
    }

    private fun updateButtonStatus() {
        button.isEnabled = hasSelectedItem()
    }

    private fun hasSelectedItem(): Boolean {
        for (item in adapter.list) {
            if (item.selected) {
                return true
            }
        }
        return false
    }

    private fun dismissDialog() {
        if (isDetached) {
            return
        }
        dismiss()
    }
}